import { nanoid } from 'nanoid';
import { useDispatch } from 'react-redux';
import { TodoType } from '../reducer/store';
import './index.scss';
import { addTodo } from '../TodoListSlice';

function Header() {
  const dispatch = useDispatch();

  const handleKeyUp = (event: React.KeyboardEvent<HTMLInputElement>) => {
    const { key, target } = event;
    if (key !== 'Enter') {
      return;
    }
    const value = (target as HTMLInputElement).value;
    if (value.trim() === '') {
      alert('输入不能为空');
      return;
    }
    const newItem: TodoType = {
      id: nanoid(5),
      name: value,
      done: false,
    };
    dispatch(addTodo(newItem));
    (target as HTMLInputElement).value = '';
  };
  return (
    <div className="header">
      <input
        type="text"
        className="input"
        placeholder="请输入你的任务，按回车键确认"
        onKeyUp={handleKeyUp}
      />
    </div>
  );
}

export default Header;
